package com.apisix.service.controller;

import com.apisix.service.entity.Consumer;
import com.apisix.service.service.ConsumerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/consumers")
public class ConsumerController {

    private final ConsumerService consumerService;

    @Autowired
    public ConsumerController(ConsumerService consumerService) {
        this.consumerService = consumerService;
    }

    @GetMapping
    public ResponseEntity<List<Consumer>> getAllConsumers() {
        List<Consumer> consumers = consumerService.getAllConsumers();
        return ResponseEntity.ok(consumers);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Consumer> getConsumerById(@PathVariable Long id) {
        return consumerService.getConsumerById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("/app/{appId}")
    public ResponseEntity<Consumer> getConsumerByAppId(@PathVariable String appId) {
        return consumerService.getConsumerByAppId(appId)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<?> createConsumer(@RequestBody Consumer consumer) {
        try {
            // 检查appId是否已存在
            if (consumerService.existsByAppId(consumer.getAppId())) {
                return ResponseEntity.badRequest().body(Map.of("error", "AppId已存在"));
            }
            
            // 如果未提供应用名称，则使用appId作为默认值
            if (consumer.getAppName() == null || consumer.getAppName().trim().isEmpty()) {
                consumer.setAppName(consumer.getAppId());
            }
            
            Consumer createdConsumer = consumerService.createConsumer(consumer);
            return ResponseEntity.status(HttpStatus.CREATED).body(createdConsumer);
        } catch (NoSuchAlgorithmException | IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "生成RSA密钥失败: " + e.getMessage()));
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> updateConsumer(@PathVariable Long id, @RequestBody Consumer consumerDetails) {
        return consumerService.updateConsumer(id, consumerDetails)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteConsumer(@PathVariable Long id) {
        boolean deleted = consumerService.deleteConsumer(id);
        if (deleted) {
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }
} 